require('./mongoose')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// var data = require('./data/category.init.json')

/**
  _id: 内嵌文档，不生成id
  name: 属性名称
  field: 属性字段
  dtype: 属性数据类型
  len: 属性值长度
  notnullable: 是否可空
  dvalue: 属性默认值
  tag: 属性标签（分组）
  enums: 枚举类型的值范围
*/
var AttrSchema = Schema({
  _id: false,
  name: String,
  field: String,
  dtype: String,
  len: { type: Number, default: 255 },
  notnullable: { type: Boolean, default: false },
  dvalue: Schema.Types.Mixed,
  tag: { type: Schema.Types.ObjectId, ref: 'Tag' },
  enums: [],
  datasource: Object
});

/**
  模型分类
  code: 唯一标识
  name: 名字
  parent: 父分类
  children: 子分类
  attrs: 类型默认属性（模型会继承默认属性）
*/
var categorySchema = Schema({
  code: { type: String, unique: true },
  name: { type: String },
  parent: { type: String },
  // children: [{type: String}],
  attrs: [AttrSchema],
})

categorySchema.statics = {
  // init: async function () {
  //   var count = await Category.count()
  //   if (count > 0) return;
  //   Category.create(data)
  // },
  page: function (query, page, limit, callback) {
    if (page === undefined) page = 0
    if (limit === undefined) limit = 20
    Category.count(query).then(total => {
      Category.find(query).skip((page) * limit).limit(limit * 1).exec().then((docs) => {
        callback({
          pageable: {
            totalElements: total,
            numberOfElements: docs.length,
            totalPages: Math.ceil(total / limit),
            number: page,
            first: page == 0,
            last: docs.length < limit || (docs.length === limit && (page + 1) * limit >= total),
            size: limit,
            fromNumber: page * limit,
            toNumber: page * limit + docs.length
          },
          docs
        })
      })
    })
  }
};

var Category = mongoose.model('Category', categorySchema);

module.exports = Category
